package com.example.javachatroomextend.component;

import com.example.javachatroomextend.constant.Constant;
import com.example.javachatroomextend.model.Message;
import com.example.javachatroomextend.model.User;
import com.example.javachatroomextend.service.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class TextWebSocket extends TextWebSocketHandler {
    private Map<Integer,WebSocketSession> hash = new HashMap<>();

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private MessageService messageService;
    @Autowired
    private TodoMessageService todoMessageService;
    @Autowired
    private UserService userService;
    @Autowired
    private NewFriendService newFriendService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
       log.info("websocket建立连接成功");
       User user = (User)session.getAttributes().get("user");
       Integer userId = user.getUserId();
       if (hash.get(userId) == null) {
           hash.put(userId,session);
       }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info(message.toString());
        Message message1 = objectMapper.readValue(message.asBytes(),Message.class);
        User user = (User) session.getAttributes().get("user");
        Integer userId = user.getUserId();
        if ("friend".equals(message1.getType())) {
            String name = message1.getContent();
            User user1 = userService.getUserByName(name);
            if (user1 == null) return;
            Integer ret = friendService.isFriends(user.getUserId(),user1.getUserId());
            if (ret != null) {
                return;
            }
            ret = newFriendService.isExist(user.getUserId(),user1.getUserId());
            if (ret != null && ret >= 0) {
                return;
            }
            WebSocketSession session1 = hash.get(user1.getUserId());
            if (session1 != null) {
                session1.sendMessage(message);
            }
            newFriendService.addNewFriend(user.getUserId(),user.getUsername(),user1.getUserId());
        }else {
            messageService.addMessage(message1.getSessionId(), userId, message1.getContent());
            Integer friendId = sessionService.getFriendUserIdBySessionId(message1.getSessionId(), userId);
            sessionService.updateLastTimeAndLastMessage(message1.getPostTime(), message1.getContent(), message1.getSessionId());
            WebSocketSession session1 = hash.get(friendId);
            stringRedisTemplate.opsForList().rightPush(Constant.key + message1.getSessionId(), objectMapper.writeValueAsString(message1));
            if (session1 != null) {
                session1.sendMessage(message);
            }else {
                todoMessageService.increaseCount(friendId,message1.getSessionId());
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error(exception.toString());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("websocket断开连接成功");
        User user = (User) session.getAttributes().get("user");
        hash.remove(user.getUserId());
    }
}
